<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>商家主页 - 酒店管理系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet" />
    <style>
        body {
            font-family: 'Inter', sans-serif;
        }

        button {
            transition: all 0.3s ease;
        }

        button:hover {
            transform: scale(1.05);
        }
    </style>
</head>
<body class="bg-gray-100">

<!-- 显示当前商家名称 -->
<div class="bg-blue-500 text-white p-4 text-center">
    <h1 id="merchantNameDisplay" class="text-2xl font-bold"></h1>
</div>

<!-- 操作按钮区域 -->
<div class="container mx-auto mt-8 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 px-4">
    <button id="modifyShopInfoBtn" class="bg-blue-500 text-white p-3 rounded-md shadow-md">
        <i class="fa-solid fa-store"></i> 修改店铺信息
    </button>
    <div class="relative">
        <button type="button" class="bg-green-500 text-white p-3 rounded-md shadow-md dropdown-toggle"
                data-dropdown-toggle="roomActionsDropdown">
            <i class="fa-solid fa-bed"></i> 增删查改房间信息
        </button>
        <div id="roomActionsDropdown"
             class="z-10 hidden bg-white divide-y divide-gray-100 rounded-md shadow w-44 dark:bg-gray-700">
            <ul class="py-1 text-sm text-gray-700 dark:text-gray-200" aria-labelledby="dropdownLargeButton">
                <li>
                    <button id="addRoomBtn"
                            class="block py-2 px-4 hover:bg-gray-100 dark:hover:bg-gray-600 dark:hover:text-white">增加</button>
                </li>
                <li>
                    <button id="deleteRoomBtn"
                            class="block py-2 px-4 hover:bg-gray-100 dark:hover:bg-gray-600 dark:hover:text-white">删除</button>
                </li>
                <li>
                    <button id="queryRoomBtn"
                            class="block py-2 px-4 hover:bg-gray-100 dark:hover:bg-gray-600 dark:hover:text-white">查询</button>
                </li>
                <li>
                    <button id="modifyRoomBtn"
                            class="block py-2 px-4 hover:bg-gray-100 dark:hover:bg-gray-600 dark:hover:text-white">修改</button>
                </li>
            </ul>
        </div>
    </div>
    <button id="customerCheckInBtn" class="bg-yellow-400 text-white p-3 rounded-md shadow-md">
        <i class="fa-solid fa-user-check"></i> 客户入住
    </button>
    <button id="agreeCancelBtn" class="bg-orange-400 text-white p-3 rounded-md shadow-md">
        <i class="fa-solid fa-ban"></i> 同意客户退订
    </button>
    <button id="viewSalesBtn" class="bg-purple-500 text-white p-3 rounded-md shadow-md">
        <i class="fa-solid fa-chart-bar"></i> 查看销量
    </button>
    <button id="blacklistCustomerBtn" class="bg-red-500 text-white p-3 rounded-md shadow-md">
        <i class="fa-solid fa-user-slash"></i> 拉黑客户
    </button>
</div>

<!-- 修改店铺信息表单 -->
<form id="modifyShopInfoForm" action="EditMerchantInfoServlet" method="post" style="display: none;">
    <input type="hidden" id="merchantName" name="merchantName">
    <input type="text" id="newName" name="newName" placeholder="新名称"><br>
    <input type="password" id="newPassword" name="newPassword" placeholder="新密码"><br>
    <input type="text" id="newAddress" name="newAddress" placeholder="新地址"><br>
    <input type="text" id="newEstablishmentYear" name="newEstablishmentYear" placeholder="新成立年份"><br>
    <input type="text" id="newContactInfo" name="newContactInfo" placeholder="新联系电话"><br>
    <input type="text" id="newKeywords" name="newKeywords" placeholder="新关键词"><br>
    <input type="submit" value="提交修改">
</form>

<!-- 增加房间信息表单 -->
<form id="addRoomForm" action="AddRoomServlet" method="post" style="display: none;">
    <input type="hidden" name="merchantName" id="addRoom_merchantName">
    <label>床型：<input type="text" name="bedType" required></label><br>
    <label>剩余数量：<input type="number" name="remainingQuantity" required></label><br>
    <label>关键词：<input type="text" name="keywords" required></label><br>
    <label>价格：<input type="number" step="0.01" name="price" required></label><br>
    <button type="submit">提交房型</button>
    <button type="button" id="cancelAddRoomBtn">取消</button>
</form>
<form id="blacklistForm" action="BlacklistCustomerServlet" method="post" style="display: none;">
    <input type="hidden" id="formMerchantName" name="merchantName">
    <input type="hidden" id="formUserId" name="userId">
    <input type="hidden" id="formReason" name="reason">
    <input type="submit" value="提交拉黑请求">
</form>

<!-- 显示查询和删除结果的区域 -->
<div id="roomManagementResult"></div>

<!-- 修改房型信息表单 -->
<div id="modifyRoomFormContainer" style="display: none;">
    <h2>修改房型信息</h2>
    <div id="modifyRoomForms"></div>
</div>
<!-- 在merchant-dashboard.html中确保这些元素存在 -->
<div id="checkInContainer" style="display: none;">
    <h2 class="text-xl font-bold mt-4">客户入住申请</h2>
    <div id="pendingOrdersList"></div>
</div>
<!-- 退款订单容器 -->
<div id="refundOrdersContainer" style="display: none;">
    <h2 class="text-xl font-bold mt-4">退款申请订单</h2>
    <div id="refundOrdersList"></div>
</div>
<!-- 在merchant-dashboard.html中添加商家信息区域 -->
<div id="merchantInfoSection" class="hidden container mx-auto mt-8 px-4">
    <h2 class="text-xl font-bold mb-4">商家销量信息</h2>
    <div id="salesVolumeContent" class="bg-white p-6 rounded-lg shadow-md">
        <!-- 销量数据将在这里显示 -->
        <p class="text-gray-500">加载中...</p>
    </div>
</div>
<script>
    // 获取 URL 中的商家名称参数
    const urlParams = new URLSearchParams(window.location.search);
    const merchantName = urlParams.get('merchantName');

    // 显示商家名称
    const merchantNameDisplay = document.getElementById('merchantNameDisplay');
    if (merchantName) {
        merchantNameDisplay.textContent = `当前商家: ${merchantName}`;
    }

    // 绑定修改店铺信息按钮点击事件
    document.getElementById('modifyShopInfoBtn').addEventListener('click', () => {
        document.getElementById('merchantName').value = merchantName;
        document.getElementById('modifyShopInfoForm').style.display = 'block';
    });


    // 绑定表单提交事件（修改店铺）
    document.getElementById('modifyShopInfoForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        const formData = new FormData(e.target);
        try {
            const response = await fetch('EditMerchantInfoServlet', {
                method: 'POST',
                body: formData
            });
            const result = await response.text();
            console.log('服务器响应:', result);
            alert(result);

            // 检查是否修改成功并更新商家名称显示
            if (result === '店铺信息修改成功') {
                const newName = document.getElementById('newName').value;
                if (newName) {
                    merchantNameDisplay.textContent = `当前商家: ${newName}`;
                    // 更新URL中的merchantName参数
                    const url = new URL(window.location.href);
                    url.searchParams.set('merchantName', newName);
                    window.history.replaceState(null, null, url.href);
                }
            }
        } catch (error) {
            console.error('请求出错:', error);
            alert('请求出错，请检查网络或稍后重试');
        }
    });

    // 修改processRefund函数，使用表单提交替代fetch
function processRefund(orderId, action) {
    if (!orderId) {
        alert('错误：缺少订单ID');
        return;
    }

    const actionText = action === 'approve' ? '同意退款' : '拒绝退款';
    if (!confirm(`确定要${actionText}吗？`)) {
        return;
    }

    // 创建隐藏表单
    const form = document.createElement('form');
    form.action = 'processRefund';
    form.method = 'POST';
    form.style.display = 'none';

    // 添加orderId字段
    const orderIdField = document.createElement('input');
    orderIdField.type = 'hidden';
    orderIdField.name = 'orderId';
    orderIdField.value = orderId;
    form.appendChild(orderIdField);

    // 添加action字段
    const actionField = document.createElement('input');
    actionField.type = 'hidden';
    actionField.name = 'action';
    actionField.value = action;
    form.appendChild(actionField);

    // 添加到文档并提交
    document.body.appendChild(form);
    form.submit();

    // 提交后移除表单
    document.body.removeChild(form);
}

    // 绑定点击“增加房型”按钮
    document.getElementById('addRoomBtn').addEventListener('click', () => {
        if (!merchantName) {
            alert("商家名称未指定");
            return;
        }
        document.getElementById('addRoom_merchantName').value = merchantName;
        document.getElementById('addRoomForm').style.display = 'block';
    });

    // 绑定取消增加房型按钮点击事件
    document.getElementById('cancelAddRoomBtn').addEventListener('click', () => {
        document.getElementById('addRoomForm').style.display = 'none';
    });

    // 绑定表单提交事件（增加房型）
    document.getElementById('addRoomForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        const formData = new FormData(e.target);
        try {
            const response = await fetch('AddRoomServlet', {
                method: 'POST',
                body: formData
            });
            const result = await response.text();
            console.log('服务器响应:', result);
            alert(result);
            document.getElementById('addRoomForm').style.display = 'none';
            // 刷新房间列表
            queryRoomTypes();
        } catch (error) {
            console.error('请求出错:', error);
            alert('请求出错，请检查网络或稍后重试');
        }
    });

    // 绑定查询房间按钮点击事件
    document.getElementById('queryRoomBtn').addEventListener('click', queryRoomTypes);

    // 查询房间类型
    async function queryRoomTypes() {
        if (!merchantName) {
            alert("商家名称未指定");
            return;
        }
        try {
            const response = await fetch(`ManageRoomServlet?merchantName=${merchantName}`);
            const result = await response.text();
            document.getElementById('roomManagementResult').innerHTML = result;
        } catch (error) {
            console.error('请求出错:', error);
            alert('请求出错，请检查网络或稍后重试');
        }
    }

    // 确认删除
    async function confirmDelete(roomTypeId, merchantName) {
        if (confirm("确定要删除该房型信息吗？")) {
            try {
                const response = await fetch(`ManageRoomServlet?action=delete&merchantName=${merchantName}&roomTypeId=${roomTypeId}`);
                const result = await response.text();
                alert(result);
                // 刷新房间列表
                queryRoomTypes();
            } catch (error) {
                console.error('请求出错:', error);
                alert('请求出错，请检查网络或稍后重试');
            }
        }
    }

    // 绑定修改房间按钮点击事件
    document.getElementById('modifyRoomBtn').addEventListener('click', async () => {
        if (!merchantName) {
            alert("商家名称未指定");
            return;
        }
        try {
            const response = await fetch(`ManageRoomServlet?action=showModifyForms&merchantName=${merchantName}`);
            const roomTypes = await response.json();
            const modifyRoomForms = document.getElementById('modifyRoomForms');
            modifyRoomForms.innerHTML = '';
            roomTypes.forEach(roomType => {
                const form = document.createElement('form');
                form.action = 'ModifyRoomServlet';
                form.method = 'post';
                form.innerHTML = `
                    <input type="hidden" name="roomTypeId" value="${roomType.roomTypeId}">
                    <input type="hidden" name="merchantName" value="${merchantName}">
                    <label>床型：<input type="text" name="bedType" value="${roomType.bedType}" required></label><br>
                    <label>剩余数量：<input type="number" name="remainingQuantity" value="${roomType.remainingQuantity}" required></label><br>
                    <label>关键词：<input type="text" name="keywords" value="${roomType.keywords}" required></label><br>
                    <label>价格：<input type="number" step="0.01" name="price" value="${roomType.price}" required></label><br>
                    <button type="submit">提交修改</button>
                `;
                modifyRoomForms.appendChild(form);
            });
            document.getElementById('modifyRoomFormContainer').style.display = 'block';
        } catch (error) {
            console.error('请求出错:', error);
            alert('请求出错，请检查网络或稍后重试');
        }
    });

    // 绑定客户入住按钮点击事件
    document.getElementById('customerCheckInBtn').addEventListener('click', async () => {
        try {
            // 获取当前商家名称
            const merchantName = urlParams.get('merchantName');
            if (!merchantName) {
                alert("商家名称未指定");
                return;
            }

            // 显示客户入住容器
            document.getElementById('checkInContainer').style.display = 'block';

            // 获取申请中的订单
            const response = await fetch(`ApproveCheckInServlet?action=list&merchantName=${merchantName}`);
            const orders = await response.json();

            // 显示订单列表
            const ordersList = document.getElementById('pendingOrdersList');
            ordersList.innerHTML = '';

            if (orders.length === 0) {
                ordersList.innerHTML = '<p class="text-gray-500">没有待处理的入住申请</p>';
                return;
            }

            // 创建订单表格
            const table = document.createElement('table');
            table.className = 'min-w-full divide-y divide-gray-200';
            table.innerHTML = `
                <thead class="bg-gray-50">
                    <tr>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">订单ID</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">客户ID</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">房型</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">床型</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">数量</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">入住时间</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">退房时间</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    ${orders.map(order => `
                        <tr>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${order.orderId}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${order.userId}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${order.roomTypeName}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${order.bedType}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${order.roomTypeQuantity}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${new Date(order.checkInTime).toLocaleDateString()}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${new Date(order.checkOutTime).toLocaleDateString()}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                <button onclick="confirmCheckIn(${order.orderId}, '${merchantName}')" class="bg-green-500 text-white px-3 py-1 rounded">同意入住</button>
                            </td>
                        </tr>
                    `).join('')}
                </tbody>
            `;

            ordersList.appendChild(table);

        } catch (error) {
            console.error('请求出错:', error);
            alert('请求出错，请检查网络或稍后重试');
        }
    });

    // 同意入住处理函数
async function confirmCheckIn(orderId, merchantName) {
    if (confirm("确定要同意该客户入住吗？")) {
        try {
            const response = await fetch(`ApproveCheckInServlet?action=approve&orderId=${orderId}&merchantName=${merchantName}`);

            // 检查HTTP状态码
            if (!response.ok) {
                throw new Error(`HTTP错误，状态码：${response.status}`);
            }

            const result = await response.text();
            alert(result);

            // 刷新订单列表
            refreshPendingOrders();

        } catch (error) {
            console.error('请求出错:', error);
            alert(`处理请求时出错：${error.message}`);
        }
    }
}

// 刷新待处理订单列表
async function refreshPendingOrders() {
    try {
        const merchantName = urlParams.get('merchantName');
        if (!merchantName) {
            alert("商家名称未指定");
            return;
        }

        const response = await fetch(`ApproveCheckInServlet?action=list&merchantName=${merchantName}`);

        // 检查HTTP状态码
        if (!response.ok) {
            throw new Error(`获取订单列表失败，状态码：${response.status}`);
        }

        // 先检查响应是否为JSON格式
        const contentType = response.headers.get('content-type');
        if (!contentType || !contentType.includes('application/json')) {
            const text = await response.text();
            throw new Error(`期望JSON响应，但得到：${text.substring(0, 100)}...`);
        }

        const orders = await response.json();
        const ordersList = document.getElementById('pendingOrdersList');
        ordersList.innerHTML = '';

        if (orders.length === 0) {
            ordersList.innerHTML = '<p class="text-gray-500">没有待处理的入住申请</p>';
            return;
        }

        // 创建订单表格
        const table = document.createElement('table');
        table.className = 'min-w-full divide-y divide-gray-200';
        table.innerHTML = `
            <thead class="bg-gray-50">
                <tr>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">订单ID</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">客户ID</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">房型</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">床型</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">数量</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">入住时间</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">退房时间</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
                ${orders.map(order => `
                    <tr>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${order.orderId}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${order.userId}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${order.roomTypeName}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${order.bedType}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${order.roomTypeQuantity}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${new Date(order.checkInTime).toLocaleDateString()}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${new Date(order.checkOutTime).toLocaleDateString()}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            <button onclick="confirmCheckIn(${order.orderId}, '${merchantName}')" class="bg-green-500 text-white px-3 py-1 rounded">同意入住</button>
                        </td>
                    </tr>
                `).join('')}
            </tbody>
        `;

        ordersList.appendChild(table);

    } catch (error) {
        console.error('刷新订单列表出错:', error);
        alert(`获取订单列表失败：${error.message}`);

        // 显示错误信息
        const ordersList = document.getElementById('pendingOrdersList');
        ordersList.innerHTML = `<p class="text-red-500">获取订单列表失败：${error.message}</p>`;
    }
}

    // 绑定同意客户退订按钮点击事件
    document.getElementById('agreeCancelBtn').addEventListener('click', async () => {
        try {
            // 获取当前商家名称
            const merchantName = urlParams.get('merchantName');
            if (!merchantName) {
                alert("商家名称未指定");
                return;
            }

            // 显示退款订单容器
            document.getElementById('refundOrdersContainer').style.display = 'block';
            document.getElementById('checkInContainer').style.display = 'none'; // 隐藏其他容器

            // 获取退款中订单
            const response = await fetch(`processRefund?action=list&merchantName=${merchantName}`);

            // 检查HTTP状态码
            if (!response.ok) {
                throw new Error(`HTTP错误，状态码：${response.status}`);
            }

            // 检查响应是否为JSON格式
            const contentType = response.headers.get('content-type');
            if (!contentType || !contentType.includes('application/json')) {
                const text = await response.text();
                throw new Error(`期望JSON响应，但得到：${text.substring(0, 100)}...`);
            }

            const orders = await response.json();

            // 显示订单列表
            const ordersList = document.getElementById('refundOrdersList');
            ordersList.innerHTML = '';

            if (orders.length === 0) {
                ordersList.innerHTML = '<p class="text-gray-500">没有待处理的退款申请</p>';
                return;
            }

            // 创建订单表格
            const table = document.createElement('table');
            table.className = 'min-w-full divide-y divide-gray-200';
            table.innerHTML = `
                <thead class="bg-gray-50">
                    <tr>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">订单ID</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">客户ID</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">房型</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">床型</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">数量</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">入住时间</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">退房时间</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">金额</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    ${orders.map(order => `
                        <tr>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${order.orderId}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${order.userId}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${order.roomTypeName}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${order.bedType}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${order.roomTypeQuantity}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${new Date(order.checkInTime).toLocaleDateString()}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${new Date(order.checkOutTime).toLocaleDateString()}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${order.totalConsumption}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                <button onclick="processRefund(${order.orderId}, 'approve')" class="bg-green-500 text-white px-3 py-1 rounded mr-2">同意退款</button>
                                <button onclick="processRefund(${order.orderId}, 'reject')" class="bg-red-500 text-white px-3 py-1 rounded">拒绝退款</button>
                            </td>
                        </tr>
                    `).join('')}
                </tbody>
            `;

            ordersList.appendChild(table);

        } catch (error) {
            console.error('请求出错:', error);
            alert('请求出错，请检查网络或稍后重试');
        }
    });

    // 查看销量按钮点击事件
document.getElementById("viewSalesBtn").addEventListener("click", function () {
    const merchantInfoSection = document.getElementById('merchantInfoSection');

    // 确保商家信息区域可见
    if (merchantInfoSection.classList.contains('hidden')) {
        merchantInfoSection.classList.remove('hidden');
    }

    // 同步并刷新销量数据
    syncAndRefreshSalesVolume();
});

// 同步并刷新销量数据
function syncAndRefreshSalesVolume() {
    // 先同步销量数据
    fetch('/SyncSalesVolumeServlet')
        .then(response => response.text())
        .then(message => {
            alert(message);
            // 同步成功后刷新商家信息
            fetchMerchantInfo();
        })
        .catch(error => {
            console.error('同步销量数据出错:', error);
            alert('同步销量数据失败，请稍后重试');
        });
}

    document.getElementById('blacklistCustomerBtn').addEventListener('click', () => {
    const merchantName = urlParams.get('merchantName');
    if (!merchantName) {
        alert("商家名称未指定");
        return;
    }

    const userId = prompt("请输入要拉黑的客户 ID");
    if (!userId) {
        alert("未输入客户 ID");
        return;
    }

    const reason = prompt("请输入拉黑原因");
    if (!reason) {
        alert("未输入拉黑原因");
        return;
    }

    document.getElementById('formMerchantName').value = merchantName;
    document.getElementById('formUserId').value = userId;
    document.getElementById('formReason').value = reason;

    document.getElementById('blacklistForm').submit();
});

    // 下拉菜单切换
    const dropdownToggle = document.querySelector('[data-dropdown-toggle="roomActionsDropdown"]');
    const dropdownMenu = document.getElementById('roomActionsDropdown');
    dropdownToggle?.addEventListener('click', () => {
        dropdownMenu.classList.toggle('hidden');
    });

    // 修改fetchMerchantInfo函数，将数据显示在merchantInfoSection中
function fetchMerchantInfo() {
    fetch('/MerchantInfoServlet')
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.text();
        })
        .then(data => {
            try {
                const merchants = JSON.parse(data);
                const salesVolumeContent = document.getElementById('salesVolumeContent');
                salesVolumeContent.innerHTML = '';

                // 找到当前商家的数据
                const currentMerchant = merchants.find(m => m.merchantName === merchantName);

                if (currentMerchant) {
                    // 显示商家销量信息
                    salesVolumeContent.innerHTML = `
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                            <div class="bg-blue-50 p-4 rounded-lg">
                                <h3 class="font-semibold text-blue-700">总销量</h3>
                                <p class="text-2xl font-bold">${currentMerchant.salesVolume || 0}</p>
                            </div>
                            <div class="bg-green-50 p-4 rounded-lg">
                                <h3 class="font-semibold text-green-700">总营业额</h3>
                                <p class="text-2xl font-bold">¥${currentMerchant.turnover || 0}</p>
                            </div>
                            <div class="bg-purple-50 p-4 rounded-lg">
                                <h3 class="font-semibold text-purple-700">收藏数</h3>
                                <p class="text-2xl font-bold">${currentMerchant.favoritesCount || 0}</p>
                            </div>
                        </div>

                        <!-- 这里可以添加更详细的销售统计图表 -->
                        <div class="mt-6">
                            <h4 class="font-semibold mb-3">销售统计</h4>
                            <div class="h-64 bg-gray-50 rounded-lg p-4">
                                <!-- 图表将在这里显示 -->
                                <p class="text-gray-500">图表数据加载中...</p>
                            </div>
                        </div>
                    `;
                } else {
                    salesVolumeContent.innerHTML = '<p class="text-red-500">未找到该商家的销量信息</p>';
                }
            } catch (error) {
                console.error('解析JSON数据出错:', error);
                salesVolumeContent.innerHTML = '<p class="text-red-500">获取销量数据失败，请稍后重试</p>';
            }
        })
        .catch(error => {
            console.error('获取商家信息出错:', error);
            salesVolumeContent.innerHTML = '<p class="text-red-500">获取销量数据失败，请稍后重试</p>';
        });
}


</script>
</body>
</html>
